package com.qinglei.recoup.longconn.controller;

import com.qinglei.recoup.longconn.service.MessageProcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.Arrays;

@Slf4j
@Controller
@RequestMapping("msg")
public class MessageController {

    @Resource
    private MessageProcService messageProcService;

    @GetMapping("/send")
    public String sendAllPage() {
        return "msg/send";
    }

    @PostMapping(value = "/send", produces = "application/x-www-form-urlencoded;charset=UTF-8")
    public String sendMessageAllClient(@NotBlank @RequestParam String funcCode, @NotBlank @RequestParam String body) {
        log.info("sendMessageAllClient funcCode:{} body:{}", funcCode, body);
        int deviceCnt = 0;
        try {
            deviceCnt = messageProcService.sendMessageAllClient(funcCode, body);
            log.info("send to device num:{}", deviceCnt);
        } catch (Exception e) {
            log.error("send down message error", e);
            return "failed";
        }
        return "msg/send";
    }

    @GetMapping("/sendSelect")
    public String sendSelectPage() {
        return "msg/send-select";
    }

    @PostMapping(value = "/sendSelect", produces = "application/x-www-form-urlencoded;charset=UTF-8")
    public String sendMessage2Client(@NotBlank @RequestParam String snStr,
                                     @NotBlank @RequestParam String funcCode,
                                     @NotBlank @RequestParam String body) {
        log.info("sendMessage2Client snStr:{} funcCode:{} body:{}", snStr, funcCode, body);
        int deviceCnt = 0;
        try {
            snStr = snStr.toUpperCase();
            String[] split = snStr.split(",");
            deviceCnt = messageProcService.sendMessage2Client(Arrays.asList(split), funcCode, body);
            log.info("send to device num:{}", deviceCnt);
        } catch (Exception e) {
            log.error("send down message error", e);
            return "failed";
        }
        return "msg/send-select";
    }
}
